<template>
  <div>
    <div class="hd">运单登记</div>
    <!-- <div class="reader-box" v-if="isScaning">
      <div class="reader" id="reader"></div>
    </div> -->

    <!-- <div v-else> -->
      <div class="main">
        <van-form :model="form" ref="uForm" @submit="onSubmit">
          <div class="form-item">
            <h3 class="title"><span class="red"></span>有无交委电子运单</h3>
            <van-field name="inoutType" :rules="[{ required: true, message: '请选择有无交委电子运单' }]">
              <template #input>
                <van-radio-group v-model="form.inoutType">
                  <van-radio :name="1" icon-size="16px">有交委电子运单</van-radio>
                  <van-radio :name="2" icon-size="16px">无交委电子运单</van-radio>
                </van-radio-group>
              </template>
            </van-field>
          </div>
          <div class="form-item" v-if="form.inoutType == 1">
            <h3 class="title"><span class="red"></span>电子运单</h3>
            <van-field
              v-model="form.transportCode"
              name="transportCode"
              label=""
              placeholder="请输入或扫描电子运单"
              clearable
              maxlength="24"
              right-icon="scan"
              @click-right-icon="onClickScanCode"
              :rules="[{ required: true, message: '电子运单不能为空' },{
                validator: value => {
                  return /^([\dA-Za-z]){24}$/
                  .test(value)
                },
                message: '请输入正确的电子运单',
                trigger: 'onBlur',
              }]"
            />
            <!-- @blur="fChangeByTransportCode" -->
            <div class="reader-box" v-if="isScaning">
              <div class="readerClose" @click="stopScan">
                <van-icon name="cross" color="#b0a3a5" size="18px"/>
              </div>
              <div id="reader" class="reader"></div>
            </div>
          </div>
          <div class="form-item">
            <h3 class="title"><span class="red"></span>承运车辆车牌号</h3>
            <div style="display: flex;">
              <van-field
                v-model="form.carNo"
                name="carNo"
                label=""
                placeholder="请输入车牌号"
                clearable
                style="margin-right: 10px;"
                :rules="[{ required: true, message: '车牌号不能为空' },
                { validator: checkCarNo, message: '请输入正确的车牌号' }
                ]"
              />
              <van-field
                v-model="form.containerNumber"
                name="containerNumber"
                label=""
                placeholder="请输入挂车车牌号"
                clearable
              />
            </div>
          </div>

          <div class="form-item">
            <h3 class="title">槽罐编号</h3>
            <van-field
              v-model="form.tankCode"
              name="tankCode"
              label=""
              maxlength="50"
              placeholder="请输入槽罐编号"
              clearable
            />
          </div>

          <div class="form-item">
            <h3 class="title"><span class="red"></span>出入目的</h3>
            <van-field name="inoutPurpose" :rules="[{ required: true, message: '请选择出入目的' }]">
              <template #input>
                <van-radio-group v-model="form.inoutPurpose">
                  <van-radio :name="1" icon-size="16px">装车</van-radio>
                  <van-radio :name="2" icon-size="16px">卸车</van-radio>
                </van-radio-group>
              </template>
            </van-field>
          </div>
          <div class="form-item">
            <h3 class="title"><span class="red"></span>是否发往外省市</h3>
            <van-field name="isTo0uter" :rules="[{ required: true, message: '请选择是否发往外省市' }]">
              <template #input>
                <van-radio-group v-model="form.isTo0uter" class="vanRadio">
                  <van-radio :name="1" icon-size="16px">是</van-radio>
                  <van-radio :name="0" icon-size="16px">否</van-radio>
                </van-radio-group>
              </template>
            </van-field>
          </div>

          <div class="form-item">
            <h3 class="title"><span class="red"></span>预计时间<span class="tips">（如无法在预计时间前装卸，请重新上报）</span></h3>
            <van-field
              v-model="form.planDate"
              name="planDate"
              label=""
              readonly
              @click="showplanDate = true"
              placeholder="请选择预计时间"
              clearable
              is-link
              :rules="[{ required: true, message: '预计时间不能为空' }]"
            />
            <van-calendar v-model="showplanDate" color="#1989fa" @confirm="(e)=>onConfirm(e,'planDate')" />
          </div>
          <div class="form-item">
            <h3 class="title"><span class="red"></span>承运企业名称<span class="tips">（请填写企业全称）</span></h3>
            <van-field
              v-model="form.belongEnterprise"
              name="belongEnterprise"
              label=""
              placeholder="请输入承运企业名称"
              clearable
              :rules="[{ required: true, message: '承运企业名称不能为空' }]"
            />
          </div>
          <div class="form-item">
            <h3 class="title"><span class="red"></span>车辆性质</h3>
            <van-field name="carType" :rules="[{ required: true, message: '请选择车辆性质' }]">
              <template #input>
                <van-radio-group v-model="form.carType">
                  <van-radio :name="item.value" icon-size="16px" v-for="item in carTypeList" :key="item.value">{{ item.text }}</van-radio>
                </van-radio-group>
              </template>
            </van-field>
            
          </div>
          <!-- <div class="form-item">
            <h3 class="title">槽罐号/挂车车牌号</h3>
            <van-field
              v-model="form.containerNumber"
              name="containerNumber"
              label=""
              maxlength="20"
              placeholder="请输入槽罐号/挂车车牌号"
              clearable
            />
          </div> -->
          <div class="form-item">
            <h3 class="title"><span class="red"></span>承运车辆驾驶员姓名</h3>
            <van-field
              v-model="form.driverName"
              name="driverName"
              label=""
              placeholder="请输入承运车辆驾驶员姓名"
              clearable
              maxlength="20"
              :rules="[{ required: true, message: '承运车辆驾驶员姓名不能为空' }]"
            />
          </div>
          <div class="form-item">
            <h3 class="title"><span class="red"></span>承运车辆驾驶员身份证号</h3>
            <van-field
              v-model="form.driverIdcard"
              name="driverIdcard"
              label=""
              placeholder="请输入承运车辆驾驶员身份证号"
              clearable
              maxlength="18"
              :rules="[{ required: true, message: '承运车辆驾驶员身份证号不能为空' },{
                validator: value => {
                  return /^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/
                  .test(value)
                },
                message: '请输入正确的身份证号格式',
                trigger: 'onBlur',
              }]"
            />
          </div>
          <div class="form-item">
            <h3 class="title"><span class="red"></span>押运员姓名</h3>
            <van-field
              v-model="form.escort"
              name="escort"
              label=""
              placeholder="请输入押运员姓名"
              clearable
              maxlength="20"
              :rules="[{ required: true, message: '押运员姓名不能为空' }]"
            />
          </div>
          <div class="form-item">
            <h3 class="title"><span class="red"></span>押运员身份证号</h3>
            <van-field
              v-model="form.escortIdcard"
              name="escortIdcard"
              label=""
              placeholder="请输入押运员身份证号"
              clearable
              maxlength="18"
              :rules="[{ required: true, message: '押运员身份证号不能为空' },{
                validator: value => {
                  return /^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/
                  .test(value)
                },
                message: '请输入正确的身份证号格式',
                trigger: 'onBlur',
              }]"
            />
          </div>
          <div class="form-item">
            <h3 class="title">收货企业名称<span class="tips">（请填写企业全称，如无企业名称则不填）</span></h3>
            
            <!-- <van-field
              v-model="form.receiveEnterpriseName"
              name="receiveEnterpriseName"
              label=""
              placeholder="请选择收货企业名称"
              is-link
              @click="showreceiveEnterpriseName = true"
            />
            <van-popup v-model="showreceiveEnterpriseName" position="bottom">
              <van-picker
                show-toolbar
                :columns="enterpriseList"
                value-key="enterpriseName"
                @confirm="e=>onConfirmsPicker(e)"
                @cancel="showreceiveEnterpriseName = false"
              />
            </van-popup> -->
          
            <div class="marginTop posDiv">
              <van-field
                name="receiveEnterpriseName"
                v-model="form.receiveEnterpriseName"
                label=""
                @change="onChange"
                placeholder="请输入收货企业名称"
              />
              <!-- 
                @input="onInputChange"
                @click-input="isShowPicker" -->
              <!-- <div class="agentSeach" v-if="searchPicker">
                <div class="closeIcon">选择收货企业名称
                  <van-icon @click="closeSearch" name="cross" color="#b0a3a5" size="20px"/>
                </div>
                <div class="generate-formWork"
                    :class="{ 'generate-selected' : index == selIndex }"
                    v-for="(item,index) in searchList"
                    :key="item.id"
                    @click="selectName(item.id,item.enterpriseName)">
                  <span>{{item.enterpriseName}}</span>
                </div>
                <div v-if="searchList.length == 0 && form.receiveEnterpriseName !== ''" class="noOptions">
                  <van-icon name="warning-o" size="20px"/>
                  暂无匹配选项
                </div>
              </div> -->
            </div>
          </div>
          
          <!-- <div class="form-item">
            <h3 class="title">收货企业信用代码</h3>
            <van-field
              v-model="form.receiveEnterpriseNo"
              name="receiveEnterpriseNo"
              label=""
              placeholder="请输入收货企业信用代码"
              clearable
            />
          </div> -->
          <div class="ft">
            <van-button type="primary" native-type="submit" :disabled="isDisabled" style="width:100%;background:#007aff;border-radius: 8px;border:0;">提交</van-button>
          </div>
        </van-form>
      </div>
    <!-- </div> -->
  </div>
</template>

<script>
import { Html5Qrcode } from 'html5-qrcode';

export default {
  data() {
    return {
      showplanDate: false,
      showreceiveEnterpriseName: false,
      enterpriseList: [],
      searchList: [],
      searchPicker: false,
      selIndex: null,
      html5Qrcode: null,
			isScaning: false,
      isDisabled: false,
      form: {
        transportCode: ''
      },
      carTypeList: [{  // 车辆性质字典接口404, 先写页面里
        value: 1,
        text: '集装箱车'
      },
      {
        value: 6,
        text: '挂车'
      },
      {
        value: 2,
        text: '槽罐车'
      },
      {
        value: 5,
        text: '管道'
      },
      {
        value: 7,
        text: '槽罐挂车'
      },
      {
        value: 8,
        text: '集装箱挂车'
      },
      {
        value: 0,
        text: '非危险化学品车'
      },
      {
        value: 3,
        text: '普通危险化学品车'
      }]
    }
  },
  created() {
   this.searchList = this.enterpriseList
  },
  mounted() {
    this.fGetEnterpriseList()

    let _data = localStorage.getItem('data')
    if(_data){
      this.form = {
        ...JSON.parse(_data)
      }
    }
  },
  methods: {
    checkCarNo(value){
      let reg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵青藏川宁琼港澳]{1}[A-Z]{1}[A-HJ-NP-Z0-9]{5}$|^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵青藏川宁琼]{1}[D|F]{1}[A-HJ-NP-Z0-9]{5}$|^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵青藏川宁琼]{1}[A-Z]{1}[0-9]{6}$|^WJ[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵青藏川宁琼]{1}[0-9]{5}$|^使[0-9]{3}[A-Z]{1}$|^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵青藏川宁琼]{1}[A-Z]{1}挂[0-9]{4}$|^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵青藏川宁琼]{1}[A-Z]{1}警[0-9]{4}$|^粤Z[A-HJ-NP-Z0-9]{4,5}(港|澳)?$/

      if(!reg.test(value)) {
        return false
      }
      return true
    },
    onClickScanCode() {
      console.log('扫码', Html5Qrcode)
      this.isScaning = true;
      let _this = this
      Html5Qrcode.getCameras().then(devices => {
        console.log('devices', devices)
        // const config = {
        //   fps: 10, //  二维码扫描每秒帧数
        //   qrbox: { width: '100%', height: '100%' }, // UI框的大小
        //   aspectRatio: 1.777778,
        //   showTorchButtonIfSupported: true,
        // }
        // this.html5Qrcode = new Html5Qrcode('reader');
        // if (devices && devices.length) {
        //   let cameraId = devices[devices.length - 1].id //后置摄像头，一般最后一个是后置摄像头
        //   //let cameraId = devices[0].id //前置摄像头
        //   this.html5Qrcode.start({ deviceId: { exact: cameraId } }, config, (decodeText, decodeResult) => {
        //     console.log('decodeText: ', decodeText)

        //     _this.form.transportCode = decodeText.split('$')[2]

        //     console.log('transportCode: ', decodeText.split('$')[2])

        //     if (decodeText) {
        //       this.stopScan();
        //       this.isScaning = false;

        //       console.log('stopScan')
        //     }
        //   }).catch(err => {
        //     scanRes.err = err
        //     router.back()
        //   })
        // } else {
        //   // 如果没有找到设备，直接启用摄像头
        //   //environment：后置摄像头  user：前置摄像头
        //   this.html5Qrcode.start({ facingMode: "environment" }, config, (decodeText, decodeResult) => {
        //     console.log('decodeText222: ', decodeText)
        //     _this.form.transportCode = decodeText.split('$')[2]
        //     console.log('transportCode222: ', decodeText.split('$')[2])

        //     if (decodeText) {
        //       this.stopScan();
        //       this.isScaning = false;

        //       console.log('stopScan222')
        //     }
        //   }).catch(err => {
        //     scanRes.err = err
        //     router.back()
        //   })
        // }

        if (devices && devices.length) {
          this.html5Qrcode = new Html5Qrcode('reader');
          this.html5Qrcode.start({
            facingMode: 'environment',
          }, {
            fps: 24,
            qrbox: 280
          }, (decodeText, decodeResult) => {
            console.log('decodeText: ', decodeText)

            _this.form.transportCode = decodeText.split('$')[2]

            console.log('transportCode: ', decodeText.split('$')[2])

            console.log('form.transportCode', this.form.transportCode)

            if (decodeText) {
              this.stopScan();
              console.log('stopScan')
            }
          }, (err) => {
            console.log(err)
          });
        }
      });
    },
    stopScan() {
      this.html5Qrcode.stop();
      this.isScaning = false;
    },
    onChange(){
      this.form.receiveEnterpriseId = 0
    },
    isShowPicker() {
      // this.searchPicker = true
      console.log('form.receiveEnterpriseName', this.form.receiveEnterpriseName)
    },
    onInputChange(val) { // 监听输入框的变化实现模糊查询
      this.form.receiveEnterpriseName = val
      if(val == ''){
        this.searchPicker = false
      }

      if (this.form.receiveEnterpriseName === '' || this.form.receiveEnterpriseName === null || this.form.receiveEnterpriseName === undefined || this.selIndex!== null) { // 去除勾选状态
        this.selIndex = null
      }
      this.searchList = this.enterpriseList.filter(i => {
        this.searchPicker = true
        return i.id.includes(val) || i.enterpriseName.includes(val)
      })

      if(this.searchList.length == 0 && this.form.receiveEnterpriseName !== ''){
        this.searchPicker = false
      }
    },
    closeSearch() { // 关闭模糊查询
      this.searchPicker = false
    },
    selectName(id,name) { // 赋值选中状态
      this.searchList.forEach( (item,index) => {
        console.log('item:', item)
        if (item.id === id && item.enterpriseName === name) {
          this.selIndex = index
          this.form.receiveEnterpriseName = name
          this.form.receiveEnterpriseId = id
          this.searchPicker = false
        }
      })
    },
    onSubmit () {
      let { inoutType, carNo, containerNumber, belongEnterprise, carType, driverName, driverIdcard, escort, escortIdcard, tankCode } = this.form
      let _data = {
        inoutType,
        carNo,
        containerNumber,
        belongEnterprise,
        carType,
        driverName,
        driverIdcard,
        escort,
        escortIdcard,
        tankCode
      }
      localStorage.setItem('data', JSON.stringify(_data))

      if(this.form.carType == 7 && this.form.tankCode == ''){
        return this.$toast('请填写槽罐编号！')
      }
      this.isDisabled = true
      this.$api.addCarInout(this.form).then(res => {
        let { code, data, msg } = res.data
        if (code === 200) {
          localStorage.setItem('data', JSON.stringify(_data))
          this.$toast('提交成功！')
          this.isDisabled = false
        }else{
          this.$toast(msg)
          this.isDisabled = false
        }
      })
    },
    fGetEnterpriseList () {  // 企业列表
      this.$api.enterpriseList().then(res => {
        if(res.data.code === 200){
          this.enterpriseList = res.data.data
          this.searchList = this.enterpriseList
        }
      })
    },
    fChangeByTransportCode (e) {  // 根据运单号查询车辆信息
      this.$api.byTransportCode({ transportCode: this.form.transportCode }).then(res => {
        if(res.data.code === 200){
          this.form = res.data.data
        }
      })
    },
    formatDate (date) {
      let Months = `${date.getMonth() + 1}` < 10 ? `0${date.getMonth() + 1}` : `${date.getMonth() + 1}`
      let Dates = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate()
      let Hours = date.getHours() < 10 ? `0${date.getHours()}` : date.getHours()
      let Minutes = date.getMinutes() < 10 ? `0${date.getMinutes()}` : date.getMinutes()
      let Seconds = date.getSeconds() < 10 ? `0${date.getSeconds()}` : date.getSeconds()
      return `${date.getFullYear()}-${Months}-${Dates} ${Hours}:${Minutes}:${Seconds}`
    },
    onConfirm (e, value) {
      this[`show${value}`] = false
      this.form[value] = this.formatDate(e)
    },
    onConfirmsPicker (e) {
      this.form.receiveEnterpriseId = e.id
      this.form.receiveEnterpriseName = e.enterpriseName
      this.showreceiveEnterpriseName = false
    }
  }
}
</script>

<style lang='less' scoped>
.hd{
  width: 100%;
  height: 40px;
  line-height: 40px;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 9999;
  color: #fff;
  text-align: center;
  font-size: 14px;
  background: #1677ff;
}

.main{
  padding: 10px 15px;
  margin-top: 42px;

  .form-item{
    padding-bottom: 10px;
  }
}
.title{
  font-size: 14px;
  color: #000;
  // font-weight: bold;
  padding-bottom: 6px;

  .red::before{
    content: '*';
    color: #f00;
    position: relative;
    top: 2px;
  }

  .tips{
    font-size: 12px;
    color: #c00;
    font-weight: normal;
  }
}
.ft{
  padding-top: 10px;
}
::v-deep .van-radio-group{
  display: flex !important;
  flex-wrap: wrap;

  .van-radio{
    font-size: 14px;
    padding: 0 20px 5px 0;
  }
  .van-radio__label{
    color: #646566;
  }
}

.posDiv{
  position: relative;
  z-index: 999;
  .closeIcon{
    display: flex;
    justify-content: center;
    line-height: 40px;
    font-size: 14px;
    /deep/.van-icon{
      position: absolute !important;
      top: 11px;
      right: 10px;
    }
  }
  .agentSeach{
    width: 100%;
    position: absolute;
    right: 1%;
    background: #fff;
    box-shadow: 0 0px 5px #e3dddd;
    .noOptions{
      text-align: center;
      color: red;
      line-height: 48px;
    }
    /deep/.van-icon{
      vertical-align: middle;
      margin-right: 5px;
      margin-top: -2px;
    }
  }
  .generate-formWork{
    color: #666;
    display: flex;
    align-items: center;
    font-size: 14px;
    margin: 0 24px;
    height: 28px;
    word-break: break-all;
  }
  .generate-selected{
    color: #494DF4;
    // background-image: url("../static/img/checked.png");
    background-repeat: no-repeat;
    background-size: 18px;
    background-position: right;
  }
}

::v-deep .vanRadio .van-radio{
  width: 80px;
}

::v-deep .van-radio__icon{
  font-size: 16px;
}

.reader-box{
  padding: 0 5px 5px 5px;
  margin-top: 5px;
  border-radius: 3px;
  border: 1px solid #e1e1e1;
  box-shadow: 0 8px 5px -5px #ccc;
}
.readerClose{
  text-align: right;
  padding: 8px 0;
  margin-bottom: 6px;
  border-bottom: 1px solid #e1e1e1;
}

// .reader-box {
//   position: fixed;
//   top: 0;
//   bottom: 0;
//   left: 0;
//   right: 0;
//   background-color: rgba(0, 0, 0, 0.5);
// }

// .reader {
//   width:100%;
//   position: absolute;
//   top: 50%;
//   left: 50%;
//   transform: translate(-50%, -50%);
// }
</style>